from user import models
from rest_framework import serializers
import re


def check_email(value):
  if not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', value):
    raise serializers.ValidationError("邮箱格式不正确")
  else:
    emaildata=models.UserModel.objects.filter(email=value)
    if emaildata:
      raise serializers.ValidationError("邮箱已存在")

def check_phone(value):
  if not re.match(r'^1[3456789]\d{9}$', value):
    raise serializers.ValidationError("手机号格式不正确")
  else:
    phonedata=models.UserModel.objects.filter(phone=value)
    if phonedata:
      raise serializers.ValidationError("手机号已存在")

def check_username(value):
  if not re.match(r'^[a-zA-Z0-9]{5,20}$', value):
    raise serializers.ValidationError("用户名格式不正确")
  else:
    user=models.UserModel.objects.filter(username=value)
    if user:
      raise serializers.ValidationError("用户名已存在")


class UserSer(serializers.ModelSerializer):
  class Meta:
    model = models.UserModel
    fields = "__all__"

    extra_kwargs = {
      "email": {
        "error_messages":{
          "required": "邮箱不能为空",
          "unique": "邮箱已存在",
        },
        "validators": [check_email]
        },
      "phone": {
        "error_messages":{
          "required": "手机号不能为空",
          "unique": "手机号已存在",
        },
        "validators": [check_phone]
      },
      "password": {
        "max_length": 10,
        "min_length": 6,
        "error_messages":{
          "required": "密码不能为空",
          "max_length": "密码长度不能超过10位",
          "min_length": "密码长度不能少于6位",
      }
      },
      "username": {
        "error_messages":{
          "required": "用户名不能为空",
          "unique": "用户名已存在",
        },
        "validators": [check_username]
      }
    }


# class CouponSer(serializers.ModelSerializer):
#   class Meta:
#     model = models.CouponModel
#     fields = "__all__"
#
# class UserCoupanSer(serializers.ModelSerializer):
#   coudata = serializers.SerializerMethodField(read_only=True)
#   def get_coudata(self,obj):
#     return {'condition':obj.coupon.condition,'name':obj.coupon.name,'price':obj.coupon.price,'start_time':obj.coupon.created_time,'end_time':obj.coupon.endtime}
#   class Meta:
#     model = models.UserCoupon
#     fields = "__all__"


class UserimgSer(serializers.ModelSerializer):
  userimo = serializers.SerializerMethodField()
  def get_userimo(self,obj):
    usercouse = models.UserModel.objects.filter(id=obj.user.id).first()
    return {'username':usercouse.username,'userimg':str(usercouse.headimg),'userid':usercouse.id}


  class Meta:
    model = models.UserImg
    fields = '__all__'














